package opencm.cli;

import java.io.PrintStream;
import java.util.List;
import java.util.Scanner;

public abstract class Acao {
	
	public abstract void executar();
	
	protected static final Scanner in = new Scanner(System.in);
	protected static final PrintStream out = System.out;
	
	@Override
	public abstract String toString();
	
	protected <E> E selecionarUm(String prompt, List<E> opcoes) {
		for (int i = 0; i < opcoes.size(); i++) {
			out.printf("[%d] %s%n", i, opcoes.get(i).toString());
		}
		
		while(true) {
			try {
				return opcoes.get(readInt(prompt));
			} catch (IndexOutOfBoundsException e) {
				// Do nothing.
			}
		}
	}
	
	protected int readInt(String prompt) {
		while(true) {
			try {
				return Integer.parseInt(readLine(prompt, true));
			} catch (NumberFormatException e) {
				out.println("Número inválido.");
			}
		}
	}
	
	protected String readLine(String prompt) {
		return readLine(prompt, false);
	}
	
	protected String readLine(String prompt, boolean notNull) {
		out.printf("%s: ", prompt);
		String line = in.nextLine();
		if (line.isEmpty()) {
			return notNull ? readLine(prompt, notNull) : null;
		} else {
			return line;
		}
	}
}
